/**
 * @file ext-polystar.js
 *
 *
 * @copyright 2010 CloudCanvas, Inc. All rights reserved
 * @copyright 2021 Optimistik SAS, Inc. All rights reserved
 * @license MIT
 *
 */

const name = 'arc'

const loadExtensionTranslation = async function (svgEditor) {
  let translationModule
  const lang = svgEditor.configObj.pref('lang')
  try {
    translationModule = await import(`./locale/${lang}.js`)
  } catch (_error) {
    console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
    translationModule = await import('./locale/en.js')
  }
  svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
}

export default {
  name,
  async init() {
    const svgEditor = this
    const { svgCanvas } = svgEditor
    const { ChangeElementCommand } = svgCanvas.history
    const addToHistory = (cmd) => { svgCanvas.undoMgr.addCommandToHistory(cmd) }
    const { $id, $click, $qq } = svgCanvas
    let selElems
    let started
    let newFO
    let p = {
      cx:0,cy:0,rx:10,ry:10,angle:0,largeArcFlag:0,sweepFlag:1,
    }
    await loadExtensionTranslation(svgEditor)

    /**
     *
     * @param {string} attr attribute to change
     * @param {string|Float} val new value
     * @returns {void}
     */
    const setAttr = (attr, val) => {
      svgCanvas.changeSelectedAttribute(attr, val)
      svgCanvas.call('changed', selElems)
    }

    /**
     * @param {Float} n angle
     * @return {Float} cotangeante
     */
    const cos = (n) => Math.cos(n)

    /**
     * @param {Float} n angle
     * @returns {Float} sec
     */
    const sin = (n) => Math.sin(n)

    const π = Math.PI

    const arc = function(deg) {
      return deg * 2 * π / 360;
    }

    const caculateEndPoint = (θ, p) => {
      var cx = p.cx + p.rx
      var cy = p.cy
      p.x = p.rx + p.rx * cos(π-θ)
      p.y = - p.ry * sin(π-θ)
    }

    const getPath = (θ,p) => {
      caculateEndPoint(arc(θ), p)
      //d="m75.12,200.6a100,100 1 1 1 51.76,-0.01"
      var d = "m" + p.cx + "," + p.cy + " a" + p.rx + "," + p.ry + " " + p.angle + " "
        + p.largeArcFlag + " " + p.sweepFlag + "  " + p.x + "," + p.y
      p.largeArcFlag = 0
      return d
    }

    return {
      name: svgEditor.i18next.t(`${name}:name`),
      // The callback should be used to load the DOM with the appropriate UI items
      callback() {
        // Add the button and its handler(s)
        // Note: the star extension needs to be loaded before the polygon extension
        const fbtitle = `${name}:title`
        const titleStar = `${name}:buttons.0.title`
        const titlePolygon = `${name}:buttons.1.title`
        const buttonTemplate = `
              <se-button id="tool_arc" title="${titlePolygon}" src="arc.svg">
              </se-button>
          `
        svgCanvas.insertChildAtIndex($qq('.basicWrap .itemWrap'), buttonTemplate, 8)

        $click($id('tool_arc'), () => {
          if (this.leftPanel.updateLeftPanel('tool_arc')) {
            svgCanvas.setMode('arc')
          }
        })
      },
      mouseDown(opts) {
        if (svgCanvas.getMode() === 'arc') {
          const fill = svgCanvas.getColor('fill')
          const stroke = svgCanvas.getColor('stroke')
          const strokeWidth = svgCanvas.getStrokeWidth()
          started = true
          //'x', 'y', 'r1', 'r2', 'angle', 'largeArcFlag', 'sweepFlag'
          p.cx = opts.start_x
          p.cy = opts.start_y

          p.rx = 1
          p.ry = 1
          var d= getPath(90,p)
          newFO = svgCanvas.addSVGElementsFromJson({
            element: 'path',
            attr: {
              d:d,
              class:'arc',
              id: svgCanvas.getNextId(),
              'stroke-width': 1
            }
          })

          return {
            started: true
          }
        }
        return undefined
      },
      mouseMove(opts) {
        if (!started) {
          return undefined
        }
        if (svgCanvas.getMode() === 'arc') {
          const fill = newFO.getAttribute('fill')
          const stroke = newFO.getAttribute('stroke')
          const strokeWidth = Number(newFO.getAttribute('stroke-width'))
          const zoom = svgCanvas.getZoom()
          let x = opts.mouse_x/zoom
          let y = opts.mouse_y/zoom

          p.rx = Math.sqrt((x - p.cx) * (x - p.cx) + (y - p.cy) * (y - p.cy)) / 1.5
          var θ = 90
          var p100 = p.rx/100
          if(p100>1 && p100<2){
            θ = 180
            p.rx =100
          }else if(p100>2){
            θ = 270
            p.rx =100
            p.largeArcFlag = 1
          }

          p.ry = p.rx
          newFO.setAttribute("d",getPath(θ,p))
          newFO.setAttribute('fill-opacity', 0)
          newFO.setAttribute('stroke', 'red')
          newFO.setAttribute('stroke-width', 2)
          return {
            started: true
          }
        }
        return undefined
      },
      mouseUp() {
        if (svgCanvas.getMode() === 'arc') {
          const edge = newFO.getAttribute('edge')
          const keep = edge !== '0'
          // svgCanvas.addToSelection([newFO], true);
          return {
            keep,
            element: newFO
          }
        }
        return undefined
      },
    }
  }
}
